<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Goods\Entity\Goods;
use Goods\Entity\GoodsDiscount;
use Goods\Entity\GoodsImage;
use Goods\Entity\GoodsInSpecGoods;
use Goods\Entity\GoodsInWholesale;
use Goods\Entity\GoodsStock;
use Goods\Entity\GoodsTag;
use User\Entity\Cart;

class CartRepository extends EntityRepository
{
    /**
     * 后台客户的购物车列表
     * @param $userId
     * @param $userGroupId
     * @return array|null
     */
    public function findUserCartGoods($userId, $userGroupId)
    {
        if(!$userId) return null;

        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select(
            'c',
            'g.classId', 'g.goodsPrice', 'g.goodsItem', 'g.brandId', 'g.goodsName', 'g.stockId', 'g.goodsWeight', 'g.goodsWeightUnit', 'g.goodsWeightConversion', 'g.goodsState', 'g.goodsType', 'g.wholesaleState', 'g.goodsIntegralBuy', 'g.goodsUserGroupPrice',
            't.stockNum', 't.stockShowState', 't.cartBuyMinNum', 't.cartBuyMaxNum', 't.personBuyMax',
            'd.discountPrice', 'd.discountStartTime', 'd.discountEndTime', 'd.discountUserGroupType', 'd.discountUserGroup',
            'i.goodsThumbnailImage',
            's.specTagId', 's.specGoodsPrice', 's.specGoodsStock', 's.specGoodsItem', 's.specGoodsWeight', 's.specGoodsUserGroupPrice',
            'w.wholesalePrice'
        )->from(Cart::class, 'c')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'c.goodsId=g.goodsId')
            ->innerJoin(GoodsStock::class, 't', Join::WITH, 'c.goodsId=t.goodsId')
            ->innerJoin(GoodsDiscount::class, 'd', Join::WITH, 'c.goodsId=d.goodsId')
            ->leftJoin(GoodsImage::class, 'i', Join::WITH, 'g.goodsImageId=i.goodsImageId')
            ->leftJoin(GoodsInSpecGoods::class, 's', Join::WITH, 'c.inSpecGoodsId=s.inSpecGoodsId')
            ->leftJoin(GoodsInWholesale::class, 'w', Join::WITH, 'c.inWholesaleId=w.inWholesaleId')
            ->where('c.userId = :userId')->setParameter('userId', $userId)
            ->orderBy('c.cartId', 'DESC');

        $cartGoodsList = $query->getQuery()->getResult();
        $cartAmount     = 0.00;
        $cartGoodsArray = [];
        if($cartGoodsList) {
            foreach ($cartGoodsList as $key => $value) {
                $goodsGroupPrice = [];
                if($value[0]->getInSpecGoodsId() > 0) {//有商品规格
                    if(!empty($value['specGoodsUserGroupPrice'])) $goodsGroupPrice = unserialize($value['specGoodsUserGroupPrice']);
                    $goodsPrice     = $value['specGoodsPrice'];
                    $goodsItem      = $value['specGoodsItem'];
                    $goodsStockOut  = $value['specGoodsStock'] < $value[0]->getBuyNum();
                    $value['specGoodsTagInfo'] = $this->getEntityManager()->getRepository(GoodsTag::class)->findGoodsTagAndTagGroup(explode('-', $value['specTagId']));
                } else {//无商品规格
                    if(!empty($value['goodsUserGroupPrice'])) $goodsGroupPrice = unserialize($value['goodsUserGroupPrice']);
                    $goodsPrice = $value['goodsPrice'];
                    $goodsItem  = $value['goodsItem'];
                    $goodsStockOut  = $value['stockNum'] < $value[0]->getBuyNum();
                }

                $value['goodsStockOut'] = $value['stockShowState'] == 0 ? $goodsStockOut : false;//缺货状态，true 缺货，false 不缺货

                //价格判断处理，会员价、批发价、正常价
                if($value['wholesaleState'] == 1 && $value['wholesalePrice'] > 0) $value['goodsPrice'] = $value['wholesalePrice'];
                else $value['goodsPrice'] = (isset($goodsGroupPrice[$userGroupId]) && $goodsGroupPrice[$userGroupId] > 0) ? $goodsGroupPrice[$userGroupId] : $goodsPrice;

                $value['goodsItem']     = $goodsItem;
                $value['goodsAmount']   = $value['goodsPrice'] * $value[0]->getBuyNum();

                $cartGoodsArray[$key]    = $value;
            }
        }

        return ['cartAmount' => $cartAmount, 'cartGoodsList' => $cartGoodsArray];
    }
    /*=======================================下面为前台使用=======================================*/
    /**
     * 会员购物车商品列表
     * @param $userId
     * @param int $goodsChecked
     * @param bool $buyNowStatus
     * @return int|mixed|string|null
     */
    public function shopCartGoodsList($userId, $goodsChecked = 0, $buyNowStatus = false)
    {
        if(!$userId) return null;

        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select(
            'c',
            'g.classId', 'g.goodsPrice', 'g.goodsItem', 'g.brandId', 'g.goodsName', 'g.stockId', 'g.goodsWeight', 'g.goodsWeightUnit', 'g.goodsWeightConversion', 'g.goodsState', 'g.goodsType', 'g.wholesaleState', 'g.goodsIntegralBuy', 'g.goodsUserGroupPrice',
            't.stockNum', 't.stockShowState', 't.cartBuyMinNum', 't.cartBuyMaxNum', 't.personBuyMax',
            'd.discountPrice', 'd.discountStartTime', 'd.discountEndTime', 'd.discountUserGroupType', 'd.discountUserGroup',
            'i.goodsThumbnailImage',
            's.specTagId', 's.specGoodsPrice', 's.specGoodsStock', 's.specGoodsItem', 's.specGoodsWeight', 's.specGoodsUserGroupPrice',
            'w.wholesalePrice'
        )->from(Cart::class, 'c')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'c.goodsId=g.goodsId')
            ->innerJoin(GoodsStock::class, 't', Join::WITH, 'c.goodsId=t.goodsId')
            ->innerJoin(GoodsDiscount::class, 'd', Join::WITH, 'c.goodsId=d.goodsId')
            ->leftJoin(GoodsImage::class, 'i', Join::WITH, 'g.goodsImageId=i.goodsImageId')
            ->leftJoin(GoodsInSpecGoods::class, 's', Join::WITH, 'c.inSpecGoodsId=s.inSpecGoodsId')
            ->leftJoin(GoodsInWholesale::class, 'w', Join::WITH, 'c.inWholesaleId=w.inWholesaleId')
            ->where('c.userId = :userId')->setParameter('userId', $userId)
            ->orderBy('c.cartId', 'DESC');

        if($goodsChecked > 0) $query->andWhere('c.goodsChecked = 1');

        if($buyNowStatus) $query->andWhere('c.buyNow = 1');//直接购买
        else $query->andWhere('c.buyNow = 0');

        return $query->getQuery()->getResult();
    }

    /**
     * @param $cartId
     * @param $userId
     * @return int|mixed|string
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function shopCartGoodsInfo($cartId, $userId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select(
            'c',
            'g.classId', 'g.goodsPrice', 'g.goodsItem', 'g.brandId', 'g.goodsName', 'g.stockId', 'g.goodsWeight', 'g.goodsWeightUnit', 'g.goodsWeightConversion', 'g.goodsState', 'g.goodsType', 'g.wholesaleState', 'g.goodsIntegralBuy', 'g.goodsUserGroupPrice',
            't.stockNum', 't.stockShowState', 't.cartBuyMinNum', 't.cartBuyMaxNum', 't.personBuyMax',
            'd.discountPrice', 'd.discountStartTime', 'd.discountEndTime', 'd.discountUserGroupType', 'd.discountUserGroup',
            's.specTagId', 's.specGoodsPrice', 's.specGoodsStock', 's.specGoodsItem', 's.specGoodsWeight', 's.specGoodsUserGroupPrice',
            'w.wholesalePrice'
        )->from(Cart::class, 'c')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'g.goodsId=c.goodsId')
            ->innerJoin(GoodsStock::class, 't', Join::WITH, 't.goodsId=c.goodsId')
            ->innerJoin(GoodsDiscount::class, 'd', Join::WITH, 'd.goodsId=c.goodsId')
            ->leftJoin(GoodsInSpecGoods::class, 's', Join::WITH, 's.inSpecGoodsId=c.inSpecGoodsId')
            ->leftJoin(GoodsInWholesale::class, 'w', Join::WITH, 'w.inWholesaleId=c.inWholesaleId')
            ->where('c.userId = :userId')->setParameter('userId', $userId)
            ->andWhere('c.cartId = :cartId')->setParameter('cartId', $cartId);

        return $query->getQuery()->getOneOrNullResult();
    }
}